{{define "content"}}
<div x-data="createUserForm()" x-init="init()">
    <!-- 页面标题 -->
    <div class="mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">创建用户</h1>
                <p class="text-gray-600">添加新的系统用户账户</p>
            </div>
            <div>
                <a href="/system/users" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center">
                    <i class="fas fa-arrow-left mr-2"></i>
                    返回用户列表
                </a>
            </div>
        </div>
    </div>

    <!-- 创建用户表单 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">用户信息</h3>
        </div>
        
        <form @submit.prevent="submitForm()" class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- 基本信息 -->
                <div class="space-y-6">
                    <h4 class="text-md font-medium text-gray-900 border-b pb-2">基本信息</h4>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">用户名 <span class="text-red-500">*</span></label>
                        <input type="text" 
                               x-model="form.username" 
                               required 
                               @blur="checkUsername()"
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        <p x-show="errors.username" class="mt-1 text-sm text-red-600" x-text="errors.username"></p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">真实姓名 <span class="text-red-500">*</span></label>
                        <input type="text" 
                               x-model="form.real_name" 
                               required 
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">密码 <span class="text-red-500">*</span></label>
                        <input type="password" 
                               x-model="form.password" 
                               required 
                               minlength="6"
                               autocomplete="new-password"
                               data-lpignore="true"
                               data-form-type="other"
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        <p class="mt-1 text-sm text-gray-500">密码长度至少6位</p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">确认密码 <span class="text-red-500">*</span></label>
                        <input type="password" 
                               x-model="form.confirm_password" 
                               required 
                               minlength="6"
                               autocomplete="new-password"
                               data-lpignore="true"
                               data-form-type="other"
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        <p x-show="errors.confirm_password" class="mt-1 text-sm text-red-600" x-text="errors.confirm_password"></p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">状态</label>
                        <select x-model="form.status" 
                                class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                            <option value="active">活跃</option>
                            <option value="inactive">停用</option>
                        </select>
                    </div>
                </div>
                
                <!-- 联系方式和角色 -->
                <div class="space-y-6">
                    <h4 class="text-md font-medium text-gray-900 border-b pb-2">联系方式</h4>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">手机号</label>
                        <input type="tel" 
                               x-model="form.phone" 
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700">邮箱</label>
                        <input type="email" 
                               x-model="form.email" 
                               @blur="checkEmail()"
                               class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500">
                        <p x-show="errors.email" class="mt-1 text-sm text-red-600" x-text="errors.email"></p>
                    </div>
                    
                    <h4 class="text-md font-medium text-gray-900 border-b pb-2 mt-8">角色分配</h4>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">选择角色</label>
                        <div class="space-y-2 max-h-64 overflow-y-auto border border-gray-300 rounded-md p-3">
                            <template x-for="role in roles" :key="role.id">
                                <label class="flex items-center p-2 hover:bg-gray-50 rounded">
                                    <input type="checkbox" 
                                           :value="role.id" 
                                           @change="toggleRole(role.id)" 
                                           :checked="form.role_ids.includes(role.id)" 
                                           class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                    <div class="ml-3">
                                        <div class="text-sm font-medium text-gray-900" x-text="role.display_name"></div>
                                        <div class="text-sm text-gray-500" x-text="role.description"></div>
                                    </div>
                                </label>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 提交按钮 -->
            <div class="mt-8 border-t pt-6 flex justify-end space-x-3">
                <a href="/system/users" class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                    取消
                </a>
                <button type="submit" 
                        :disabled="isSubmitting"
                        class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50">
                    <span x-show="isSubmitting">
                        <i class="fas fa-spinner fa-spin mr-2"></i>处理中...
                    </span>
                    <span x-show="!isSubmitting">创建用户</span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function createUserForm() {
    return {
        // 表单数据
        form: {
            username: '',
            real_name: '',
            password: '',
            confirm_password: '',
            phone: '',
            email: '',
            status: 'active',
            role_ids: []
        },
        
        // 错误信息
        errors: {
            username: '',
            email: '',
            confirm_password: ''
        },
        
        // 状态
        isSubmitting: false,
        roles: [],
        
        // 初始化
        async init() {
            await this.loadRoles();
        },
        
        // 加载角色列表
        async loadRoles() {
            try {
                const response = await fetch('/api/v1/system/roles');
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.roles = result.data.list || [];
                } else {
                    console.warn('加载角色列表失败:', result.message);
                    this.roles = [];
                }
            } catch (error) {
                console.error('加载角色列表失败:', error);
                this.showToast('加载角色列表失败', 'error');
                this.roles = [];
            }
        },
        
        // 检查用户名是否存在
        async checkUsername() {
            if (!this.form.username) return;
            
            try {
                const response = await fetch(`/api/v1/users/check-username?username=${encodeURIComponent(this.form.username)}`);
                const result = await response.json();
                
                if (result.code === 200 && result.data && result.data.exists) {
                    this.errors.username = '该用户名已被使用';
                } else {
                    this.errors.username = '';
                }
            } catch (error) {
                console.error('检查用户名失败:', error);
            }
        },
        
        // 检查邮箱是否存在
        async checkEmail() {
            if (!this.form.email) return;
            
            try {
                const response = await fetch(`/api/v1/users/check-email?email=${encodeURIComponent(this.form.email)}`);
                const result = await response.json();
                
                if (result.code === 200 && result.data && result.data.exists) {
                    this.errors.email = '该邮箱已被使用';
                } else {
                    this.errors.email = '';
                }
            } catch (error) {
                console.error('检查邮箱失败:', error);
            }
        },
        
        // 切换角色选择
        toggleRole(roleId) {
            const numericRoleId = parseInt(roleId);
            const index = this.form.role_ids.indexOf(numericRoleId);
            
            if (index > -1) {
                // 如果已选中，则移除
                this.form.role_ids.splice(index, 1);
            } else {
                // 如果未选中，则添加
                this.form.role_ids.push(numericRoleId);
            }
        },
        
        // 验证表单
        validateForm() {
            let isValid = true;
            
            // 检查密码确认
            if (this.form.password !== this.form.confirm_password) {
                this.errors.confirm_password = '两次输入的密码不一致';
                isValid = false;
            } else {
                this.errors.confirm_password = '';
            }
            
            // 检查用户名和邮箱错误
            if (this.errors.username || this.errors.email) {
                isValid = false;
            }
            
            return isValid;
        },
        
        // 提交表单
        async submitForm() {
            if (!this.validateForm()) return;
            
            this.isSubmitting = true;
            
            try {
                const response = await fetch('/api/v1/users', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: this.form.username,
                        real_name: this.form.real_name,
                        password: this.form.password,
                        phone: this.form.phone,
                        email: this.form.email,
                        status: this.form.status,
                        role_ids: this.form.role_ids
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('用户创建成功', 'success');
                    // 跳转到用户列表页
                    setTimeout(() => {
                        window.location.href = '/system/users';
                    }, 1500);
                } else {
                    throw new Error(result.message || '创建用户失败');
                }
            } catch (error) {
                console.error('创建用户失败:', error);
                // 显示具体的错误消息
                const errorMessage = error.message || '创建用户失败';
                this.showToast(errorMessage, 'error');
            } finally {
                this.isSubmitting = false;
            }
        },
        
        // 显示提示消息
        showToast(message, type = 'info') {
            if (window.showToast) {
                window.showToast(message, type);
            } else {
                // 降级方案
                console.log(`${type}: ${message}`);
                alert(message);
            }
        }
    };
}
</script>
{{end}}